from app import app, db
from models import User, Tag, Milestone
from werkzeug.security import generate_password_hash

# 创建应用上下文
with app.app_context():
    # 创建所有数据库表
    db.create_all()

    # 添加初始用户
    if not User.query.filter_by(username='admin').first():
        admin_password = generate_password_hash('admin123', method='sha256')
        admin = User(username='admin', email='admin@example.com', password=admin_password)
        db.session.add(admin)
        db.session.commit()
        print('管理员用户创建成功：用户名=admin, 密码=admin123')
    else:
        print('管理员用户已存在')

    # 添加初始标签
    default_tags = ['bug', 'feature', 'task', 'question', 'documentation']
    for tag_name in default_tags:
        if not Tag.query.filter_by(name=tag_name).first():
            tag = Tag(name=tag_name)
            db.session.add(tag)
    db.session.commit()
    print('初始标签添加成功')

    # 添加初始里程碑
    default_milestones = [
        {'name': 'v1.0', 'description': '第一个版本', 'due_date': None},
        {'name': 'v1.1', 'description': '第二个版本', 'due_date': None}
    ]
    for ms in default_milestones:
        if not Milestone.query.filter_by(name=ms['name']).first():
            milestone = Milestone(
                name=ms['name'],
                description=ms['description'],
                due_date=ms['due_date']
            )
            db.session.add(milestone)
    db.session.commit()
    print('初始里程碑添加成功')

print('数据库初始化完成！')